﻿using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using Dapper;
using Dapper.Contrib.Extensions;

namespace EC.Application.Impl
{
    using EC.Application.Interface;
    using EC.Entity;
    using EC.Entity.Enum;
    using EC.Entity.Query;
    using EC.Entity.Request.PaymentRecord;
    using EC.Entity.Response.PaymentRecord;
    using EC.Entity.Tables;
    using System.Data;
    using System.Text.RegularExpressions;

    public class PaymentRecordServiceImpl : PaymentRecordService
    {
        #region 注入
        /// <summary>
        /// 数据接口
        /// </summary>
        private readonly IDBSession _dbSession;


        /// <summary>
        /// 数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public PaymentRecordServiceImpl(IDBSession dbSession)
        {
            _dbSession = dbSession;
        }
        #endregion

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public PaymentRecordResponse Get(int id)
        {
            var model = _dbSession.DbConnection.QueryFirst<PaymentRecordResponse>("select *  from paymentrecord where Id=@Id", new { Id = id });
            if (model != null)
            {
                return model;
            }

            return null;
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <returns></returns>
        public JResult Audit(AuditRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var settle = _dbSession.DbConnection.QueryFirst<PaymentRecord>("select * from paymentrecord where Id=@Id", new { Id = request.Id });
                if (settle == null)
                {
                    throw new Exception("付款记录不存在.");
                }

                if (settle.PaymentStatus != (int)PaymentRecordStatus.未付款)
                {
                    throw new Exception("此状态无法操作");
                }

                if (settle.HandBy > 0)
                {
                    throw new Exception("已锁定用户");
                }

                var updateSql = "UPDATE paymentrecord SET PaymentStatus=@Status,HandBy=@HandBy,ProxyMerchantId=@ProxyMerchantId WHERE Id=@Id";

                int result = _dbSession.DbConnection.Execute(updateSql, new { Status = (int)PaymentRecordStatus.付款中, HandBy = request.UserId, ProxyMerchantId = request.MerchantId, Id = request.Id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 确认付款
        /// </summary>
        public JResult Confirm(ConfirmRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                //事务开始
                //_dbSession.Begin();

                var paymentRecord = _dbSession.DbConnection.QueryFirst<PaymentRecord>("select * from paymentrecord where Id=@Id", new { Id = request.Id });
                if (paymentRecord == null)
                {
                    throw new Exception("付款记录不存在.");
                }

                if (paymentRecord.PaymentStatus != (int)PaymentRecordStatus.付款中)
                {
                    throw new Exception("此状态无法操作");
                }

                if (paymentRecord.HandBy != request.UserId)
                {
                    throw new Exception("无法操作,你并非锁定用户");
                }

                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = paymentRecord.MerchantId });

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    throw new Exception("暂无记录.");
                }
                //更新付款记录
                var updateSql = "UPDATE paymentrecord SET PaymentStatus=@PaymentStatus,PaymentDate=@PaymentDate,HandTime=@HandTime,Remark=@Remark WHERE Id=@Id";
                int result = _dbSession.DbConnection.Execute(updateSql, new { PaymentStatus = (int)PaymentRecordStatus.付款成功, PaymentDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), HandTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Remark = request.Remark, Id = paymentRecord.Id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }


                response.Success = true;
                response.Message = "操作成功.";
                //提交事务
                //_dbSession.Commit();
            }
            catch (Exception ex)
            {
                //_dbSession.Rollback();
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 取消付款
        /// </summary>
        public JResult Cancel(CancelRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                //事务开始
                _dbSession.Begin(IsolationLevel.Serializable);

                var paymentRecord = _dbSession.DbConnection.QueryFirst<PaymentRecord>("select * from paymentrecord where Id=@Id", new { Id = request.Id }, _dbSession.DbTransaction);
                if (paymentRecord == null)
                {
                    response.Message = "付款记录不存在.";
                    return response;
                }

                if (paymentRecord.PaymentStatus != (int)PaymentRecordStatus.付款中)
                {
                    response.Message = "此状态无法操作.";
                    return response;
                }

                if (paymentRecord.HandBy != request.UserId)
                {
                    response.Message = "无法操作,你并非锁定用户.";
                    return response;
                }

                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = paymentRecord.MerchantId }, _dbSession.DbTransaction);

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    response.Message = "暂无记录.";
                    return response;
                }

                //更新账户
                int merchantUpdateStatus = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance+@WithdrawalAmount WHERE Id=@Id", new { WithdrawalAmount = paymentRecord.WithdrawalAmount, Id = merchant.Id }, _dbSession.DbTransaction);
                if (merchantUpdateStatus <= 0)
                {
                    throw new Exception("更新账户失败");
                }
                //增加付款余额日志
                var paymentBalanceLog = new BalanceLog()
                {
                    MerchantId = merchant.Id,
                    Source = (int)BalanceLogSource.代付失败,
                    Type = (int)BalanceLogType.加,
                    Amount = paymentRecord.WithdrawalAmount,
                    BeforeBalance = merchant.DepositBalance,
                    AfterBalance = merchant.DepositBalance + paymentRecord.WithdrawalAmount,
                    Remark = $"付款失败 订单号：{paymentRecord.Id}",
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };
                long paymentBalanceLogResultId = _dbSession.DbConnection.Insert<BalanceLog>(paymentBalanceLog, _dbSession.DbTransaction);
                if (paymentBalanceLogResultId <= 0)
                {
                    throw new Exception("新增存款余额日志失败.");
                }

                //更新付款记录
                var updateSql = "UPDATE paymentrecord SET PaymentStatus=@PaymentStatus,PaymentDate=@PaymentDate,HandTime=@HandTime,Remark=@Remark WHERE Id=@Id";
                int result = _dbSession.DbConnection.Execute(updateSql, new { PaymentStatus = (int)PaymentRecordStatus.付款失败, PaymentDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), HandTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Remark = request.Remark, Id = paymentRecord.Id }, _dbSession.DbTransaction);
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }


                response.Success = true;
                response.Message = "操作成功.";
                //提交事务
                _dbSession.Commit();
            }
            catch (Exception ex)
            {
                _dbSession.Rollback();
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 取消付款
        /// </summary>
        public JResult Undo(CancelRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                //事务开始
                _dbSession.Begin(IsolationLevel.Serializable);

                var paymentRecord = _dbSession.DbConnection.QueryFirst<PaymentRecord>("select * from paymentrecord where Id=@Id", new { Id = request.Id }, _dbSession.DbTransaction);
                if (paymentRecord == null)
                {
                    response.Message = "付款记录不存在.";
                    return response;
                }

                var status = new List<int>
                {
                    (int)PaymentRecordStatus.付款成功,
                    (int)PaymentRecordStatus.付款中
                };

                if (!status.Any(c => c == paymentRecord.PaymentStatus))
                {
                    response.Message = "此状态无法操作.";
                    return response;
                }

                if (paymentRecord.HandBy != request.UserId)
                {
                    response.Message = "无法操作,你并非锁定用户.";
                    return response;
                }

                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = paymentRecord.MerchantId }, _dbSession.DbTransaction);

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    response.Message = "暂无记录.";
                    return response;
                }

                //更新账户
                int merchantUpdateStatus = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance+@WithdrawalAmount WHERE Id=@Id", new { WithdrawalAmount = paymentRecord.WithdrawalAmount, Id = merchant.Id }, _dbSession.DbTransaction);
                if (merchantUpdateStatus <= 0)
                {
                    throw new Exception("更新账户失败");
                }
                //增加付款余额日志
                var paymentBalanceLog = new BalanceLog()
                {
                    MerchantId = merchant.Id,
                    OrderNo = paymentRecord.Id,
                    Source = (int)BalanceLogSource.代付失败,
                    Type = (int)BalanceLogType.加,
                    Amount = paymentRecord.WithdrawalAmount,
                    BeforeBalance = merchant.DepositBalance,
                    AfterBalance = merchant.DepositBalance + paymentRecord.WithdrawalAmount,
                    Remark = $"付款失败 订单号：{paymentRecord.Id}",
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };
                long paymentBalanceLogResultId = _dbSession.DbConnection.Insert<BalanceLog>(paymentBalanceLog, _dbSession.DbTransaction);
                if (paymentBalanceLogResultId <= 0)
                {
                    throw new Exception("新增存款余额日志失败.");
                }

                //更新付款记录
                var updateSql = "UPDATE paymentrecord SET PaymentStatus=@PaymentStatus,NoticeStatus=@NoticeStatus,PaymentDate=@PaymentDate,HandTime=@HandTime,Remark=@Remark WHERE Id=@Id";
                int result = _dbSession.DbConnection.Execute(updateSql, new { PaymentStatus = (int)PaymentRecordStatus.付款失败, NoticeStatus = (int)NoticeStatusStatus.未通知, PaymentDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), HandTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Remark = request.Remark, Id = paymentRecord.Id }, _dbSession.DbTransaction);
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                response.Success = true;
                response.Message = "操作成功.";
                //提交事务
                _dbSession.Commit();
            }
            catch (Exception ex)
            {
                _dbSession.Rollback();
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 恢复成功
        /// </summary>
        public JResult ReturnSuccess(CancelRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var paymentRecord = _dbSession.DbConnection.QueryFirst<PaymentRecord>("select * from paymentrecord where Id=@Id", new { Id = request.Id });
                if (paymentRecord == null)
                {
                    response.Message = "付款记录不存在.";
                    return response;
                }

                if (paymentRecord.HandBy != request.UserId)
                {
                    response.Message = "无法操作,你并非锁定用户.";
                    return response;
                }

                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = paymentRecord.MerchantId });

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    response.Message = "暂无记录.";
                    return response;
                }

                //事务开始
                _dbSession.Begin();

                //更新账户
                int merchantUpdateStatus = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance-@DepositBalance WHERE Id=@Id", new { DepositBalance = paymentRecord.WithdrawalAmount, Id = merchant.Id }, _dbSession.DbTransaction);
                if (merchantUpdateStatus <= 0)
                {
                    throw new Exception("更新账户失败");
                }
                //增加付款余额日志
                var paymentBalanceLog = new BalanceLog()
                {
                    MerchantId = merchant.Id,
                    OrderNo = paymentRecord.Id,
                    Source = (int)BalanceLogSource.恢复成功,
                    Type = (int)BalanceLogType.减,
                    Amount = paymentRecord.WithdrawalAmount,
                    BeforeBalance = merchant.DepositBalance,
                    AfterBalance = merchant.DepositBalance - paymentRecord.WithdrawalAmount,
                    Remark = $"恢复成功 订单号：{paymentRecord.Id}",
                    CreatedBy = request.UserId,
                    CreatedDate = DateTime.Now
                };
                long paymentBalanceLogResultId = _dbSession.DbConnection.Insert<BalanceLog>(paymentBalanceLog, _dbSession.DbTransaction);
                if (paymentBalanceLogResultId <= 0)
                {
                    throw new Exception("新增存款余额日志失败.");
                }

                //更新付款记录
                var updateSql = "UPDATE paymentrecord SET PaymentStatus=@PaymentStatus,NoticeStatus=@NoticeStatus WHERE Id=@Id";
                int result = _dbSession.DbConnection.Execute(updateSql, new { PaymentStatus = (int)PaymentRecordStatus.付款成功, NoticeStatus = (int)NoticeStatusStatus.未通知, Id = paymentRecord.Id }, _dbSession.DbTransaction);
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }

                response.Success = true;
                response.Message = "操作成功.";
                //提交事务
                _dbSession.Commit();
            }
            catch (Exception ex)
            {
                _dbSession.Rollback();
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 重置
        /// </summary>
        /// <returns></returns>
        public JResult Reset(int id)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var paymentRecords = _dbSession.DbConnection.Query<PaymentRecord>("select * from paymentrecord where Id=@Id", new { Id = id });

                var paymentRecord = paymentRecords.FirstOrDefault();
                if (paymentRecord == null)
                {
                    throw new Exception("暂无存款记录.");
                }

                if (paymentRecord.NoticeStatus == (int)NoticeStatusStatus.通知失败 && paymentRecord.NoticeTimes >= 5)
                {
                    var updateSql = "UPDATE paymentrecord SET NoticeStatus=@NoticeStatus,NoticeTimes=@NoticeTimes WHERE Id=@Id";

                    int result = _dbSession.DbConnection.Execute(updateSql, new { NoticeStatus = (int)NoticeStatusStatus.未通知, NoticeTimes = 0, Id = paymentRecord.Id });
                    if (result <= 0)
                    {
                        throw new Exception("更新失败");
                    }

                    response.Success = true;
                    response.Message = "操作成功.";
                }
                else
                {
                    throw new Exception("操作失败,必须为通知失败且通知次数等于5");
                }

            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        public JResult PaymentRecordImport(List<PaymentRecord> paymentRecords, int userId, int merchantId)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                //事务开始
                _dbSession.Begin();



                paymentRecords.ForEach(item =>
                {

                    var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = merchantId }, _dbSession.DbTransaction);

                    var merchant = merchants.FirstOrDefault();
                    if (merchant == null)
                    {
                        throw new Exception("暂无记录.");
                    }

                    var sum = paymentRecords.Sum(c => c.WithdrawalAmount);
                    if (merchant.DepositBalance < item.WithdrawalAmount)
                    {
                        throw new Exception("余额不足.");
                    }
                    //更新账户
                    int merchantUpdateStatus = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance-@WithdrawalAmount,DepositFrozenBalance=DepositFrozenBalance+@WithdrawalAmount WHERE Id=@Id", new { WithdrawalAmount = item.WithdrawalAmount, Id = merchant.Id }, _dbSession.DbTransaction);
                    if (merchantUpdateStatus <= 0)
                    {
                        throw new Exception("更新账户失败");
                    }

                    //增加付款余额日志
                    var paymentBalanceLog = new BalanceLog()
                    {
                        MerchantId = merchant.Id,
                        Source = (int)BalanceLogSource.付款余额,
                        Type = (int)BalanceLogType.减,
                        Amount = item.WithdrawalAmount,
                        BeforeBalance = merchant.DepositBalance,
                        AfterBalance = merchant.DepositBalance + item.WithdrawalAmount,
                        Remark = $"批量导入预付 订单号：{item.Id}",
                        CreatedBy = userId,
                        CreatedDate = DateTime.Now
                    };
                    long paymentBalanceLogResultId = _dbSession.DbConnection.Insert<BalanceLog>(paymentBalanceLog, _dbSession.DbTransaction);
                    if (paymentBalanceLogResultId <= 0)
                    {
                        throw new Exception("新增存款余额日志失败.");
                    }

                });

                response.Success = true;
                response.Message = "操作成功.";
                //提交事务
                _dbSession.Commit();
            }
            catch (Exception ex)
            {
                _dbSession.Rollback();
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="paymentRecord"></param>
        public JResult BatchAdd(List<BatchPaymentRecord> batchPaymentRecords, int userId, int merchantId)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                if (batchPaymentRecords.Count == 0)
                {
                    throw new Exception("代付行不能为空.");
                }

                var merchants = _dbSession.DbConnection.Query<Merchant>("select * from merchant where Id=@Id", new { Id = merchantId });

                var merchant = merchants.FirstOrDefault();
                if (merchant == null)
                {
                    throw new Exception("暂无商户记录.");
                }

                if (merchant.PaymentSingle <= 0)
                {
                    throw new Exception("请联系管理员设置单笔支付金额.");
                }

                var query = (from p in batchPaymentRecords
                             where p.Push == 1//检查需要推送的数据
                             group p by p.MerchantOrderNo into g
                             where g.Count() > 1
                             select new
                             {
                                 MerchantOrderNo = g.Key,
                                 Count = g.Count()
                             });

                if (query.Count() > 0)
                {
                    throw new Exception("订单号存在重复.");
                }



                var paymentRecords = new List<PaymentRecord>();


                batchPaymentRecords.ForEach(item =>
                {


                    if (item.Push == 1)
                    {
                        if (string.IsNullOrEmpty(item.MerchantOrderNo))
                        {
                            throw new Exception("商户订单号不能为空.");
                        }
                    }
                    else
                    {
                        item.MerchantOrderNo = Guid.NewGuid().ToString("N"); ;
                    }

                    //姓名
                    if (string.IsNullOrEmpty(item.WithdrawalCardName))
                    {
                        throw new Exception("姓名不能为空.");
                    }

                    //卡号
                    if (string.IsNullOrEmpty(item.WithdrawalCardNumber))
                    {
                        throw new Exception("卡号不能为空.");
                    }

                    var withdrawalCardNumberReg = new Regex(@"^\d{10,20}$");
                    if (!withdrawalCardNumberReg.IsMatch(item.WithdrawalCardNumber))
                    {
                        throw new Exception("卡号必须介于 10 和 20 之间数字");
                    }

                    //金额
                    if (string.IsNullOrEmpty(item.WithdrawalAmount))
                    {
                        throw new Exception("金额不能为空.");
                    }

                    decimal withdrawalAmount;

                    try
                    {
                        withdrawalAmount = Convert.ToDecimal(item.WithdrawalAmount);
                    }
                    catch (Exception)
                    {
                        throw new Exception("提款金额货币格式有误.");
                    }

                    paymentRecords.Add(new PaymentRecord()
                    {
                        MerchantId = merchantId,
                        MerchantOrderNo = item.MerchantOrderNo,
                        WithdrawalAmount = withdrawalAmount + merchant.PaymentSingle,
                        WithdrawalFee = merchant.PaymentSingle,
                        WithdrawalBankName = item.WithdrawalBankName,
                        WithdrawalCardName = item.WithdrawalCardName,
                        WithdrawalCardNumber = item.WithdrawalCardNumber,
                        PaymentStatus = (int)PaymentRecordStatus.未付款,
                        PaymentDate = null,
                        TransferFee = 0,
                        NoticeStatus = item.Push == 1 ? (int)NoticeStatusStatus.未通知 : (int)NoticeStatusStatus.不通知,
                        NoticeLastTime = null,
                        NoticeTimes = 0,
                        ProxyMerchantId = 0,
                        CreatedBy = userId,
                        CreatedDate = DateTime.Now
                    });
                });

                var sum = paymentRecords.Sum(c => c.WithdrawalAmount);

                //验证订单金额
                if (merchant.DepositBalance < sum)
                {
                    throw new Exception("余额不足.");
                }

                if (paymentRecords != null && paymentRecords.Any())
                {
                    try
                    {
                        _dbSession.Begin(IsolationLevel.Serializable);

                        paymentRecords.ForEach(item =>
                        {
                            _dbSession.DbConnection.Insert(item, _dbSession.DbTransaction);
                            var id = _dbSession.DbConnection.ExecuteScalar("SELECT LAST_INSERT_ID()", null, _dbSession.DbTransaction);

                            //查询余额
                            var merchantsBalance = _dbSession.DbConnection.ExecuteScalar("select DepositBalance from merchant where Id=@Id", new { Id = merchantId }, _dbSession.DbTransaction);

                            //更新账户
                            int merchantUpdateStatus = _dbSession.DbConnection.Execute("UPDATE merchant SET DepositBalance=DepositBalance-@WithdrawalAmount,DepositFrozenBalance=DepositFrozenBalance+@WithdrawalAmount WHERE Id=@Id",
                                new { item.WithdrawalAmount, merchant.Id }, _dbSession.DbTransaction);

                            if (merchantUpdateStatus <= 0)
                            {
                                throw new Exception("更新账户失败");
                            }

                            #region 更新余额日志
                            var paymentBalanceLog = new BalanceLog()
                            {
                                MerchantId = merchant.Id,
                                OrderNo = Convert.ToInt32(id),
                                Source = (int)BalanceLogSource.预付,
                                Type = (int)BalanceLogType.减,
                                Amount = item.WithdrawalAmount,
                                BeforeBalance = Convert.ToDecimal(merchantsBalance),
                                AfterBalance = Convert.ToDecimal(merchantsBalance) - item.WithdrawalAmount,
                                Remark = $"批量手工订单预付(订单号:{id},金额{item.WithdrawalAmount})",
                                CreatedBy = 0,
                                CreatedDate = DateTime.Now
                            };

                            var logInsertStatus = _dbSession.DbConnection.Insert(paymentBalanceLog, _dbSession.DbTransaction);

                            if (logInsertStatus <= 0)
                            {
                                throw new Exception("更新余额日志失败");
                            }
                            #endregion
                        });

                        _dbSession.Commit();
                        response.Success = true;
                    }
                    catch (Exception ex)
                    {
                        _dbSession.Rollback();
                        response.Message = ex.Message;
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<PaymentRecordQueryResponse> GetPager(PaymentRecordQuery query)
        {
            //var currentPageIndex = 0;

            //if (query.CurrentPageIndex.Value > 0)
            //{
            //    currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            //}

            var files = "p.Id,p.MerchantId,p.MerchantOrderNo,p.WithdrawalAmount,p.WithdrawalFee,p.WithdrawalBankName,p.WithdrawalCardNumber,p.WithdrawalCardName,p.PaymentStatus,p.PaymentDate,p.TransferFee,p.NoticeStatus,p.NoticeLastTime,p.NoticeTimes,p.ReqeustBody,p.NoticeFail,p.Remark,p.HandTime,p.HandBy,p.CreatedBy,p.CreatedDate,m.Name as MerchantName,u.account AS _HandBy,(SELECT Name FROM merchant WHERE id=p.ProxyMerchantId) as ProxyMerchantName";
            var tableName = "paymentrecord p INNER JOIN merchant m on p.MerchantId=m.Id   LEFT JOIN user u ON u.id=p.handby ";
            var orderby = "ORDER BY Id DESC";
            var where = $"where p.MerchantId in ({string.Join(", ", query.MerchantIds)})";

            #region 条件
            if (!string.IsNullOrEmpty(query.MerchantOrderNo))
            {
                where += string.Format(" And p.MerchantOrderNo ='{0}'", query.MerchantOrderNo);
            }

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                where += string.Format(" And p.CreatedDate between '{0}' and '{1}'", query.StartTime, query.EndTime);
            }

            if (query.PaymentStatus.HasValue)
            {
                if (query.PaymentStatus.Value == 100)
                {
                    where += "And p.PaymentStatus in (1, 4)";
                }
                else
                {
                    where += string.Format(" And p.PaymentStatus ={0}", query.PaymentStatus.Value);
                }
            }

            if (query.NoticeStatus.HasValue)
            {
                where += string.Format(" And p.NoticeStatus ={0}", query.NoticeStatus.Value);
            }

            //处理人
            if (!string.IsNullOrEmpty(query.HandBy))
            {
                where += string.Format("  AND u.account='{0}'", query.HandBy);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, (query.Page.Value - 1) * query.Rows.Value, query.Rows.Value);

            //查询汇总
            var countSql = string.Format("SELECT sum(WithdrawalAmount)-SUM(WithdrawalFee) as WithdrawalAmount,SUM(WithdrawalFee) as WithdrawalFee FROM {1} {2};", files, tableName, where);

            var totalAmount = new decimal(0);
            var totalFee = new decimal(0);

            var total = _dbSession.DbConnection.QueryFirst<PaymentRecordQueryResponse>(countSql);
            if (total != null)
            {
                totalAmount = total.WithdrawalAmount;
                totalFee = total.WithdrawalFee;
            }

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<PaymentRecordQueryResponse>();

                #region
                var rows = new List<PaymentRecordQueryResponse>();
                var sum = new decimal(0);
                var feeSum = new decimal(0);

                var counts = 0;
                foreach (var item in list)
                {
                    sum += (item.WithdrawalAmount - item.WithdrawalFee);
                    feeSum += item.WithdrawalFee;
                    counts++;

                    var model = new PaymentRecordQueryResponse();
                    model.Id = item.Id;
                    model._Id = item.Id.ToString();
                    model.MerchantName = item.MerchantName;
                    model.MerchantOrderNo = item.MerchantOrderNo;
                    model._WithdrawalAmount = (item.WithdrawalAmount - item.WithdrawalFee).ToString("#0.00");
                    model._WithdrawalFee = item.WithdrawalFee.ToString("#0.00");
                    model.WithdrawalBankName = item.WithdrawalBankName;
                    model.WithdrawalCardNumber = "";
                    if (item.HandBy.HasValue && query.UserId == item.HandBy.Value)
                    {
                        model.WithdrawalCardNumber = item.WithdrawalCardNumber;
                    }
                    model.WithdrawalCardName = item.WithdrawalCardName;
                    model.PaymentStatus = item.PaymentStatus;
                    model._PaymentDate = item.PaymentDate.HasValue ? item.PaymentDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model.TransferFee = item.TransferFee;
                    model.NoticeStatus = item.NoticeStatus;
                    model._NoticeLastTime = item.NoticeLastTime.HasValue ? item.NoticeLastTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model.NoticeTimes = item.NoticeTimes;
                    model.NoticeFail = item.NoticeFail;
                    model.Remark = item.Remark;
                    model._HandTime = item.HandTime.HasValue ? item.HandTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model._HandBy = string.IsNullOrEmpty(item._HandBy) ? "" : item._HandBy;
                    model._CreatedDate = item.CreatedDate.ToString("yyyy-MM-dd HH:mm:ss");
                    model.ProxyMerchantName = item.ProxyMerchantName;
                    model.CreatedDateMinutes = DateTime.Now.Subtract(item.CreatedDate).TotalMinutes;
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("PaymentRecord0002")))
                    {
                        model.AuditPermission = "PaymentRecord0002";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("PaymentRecord0003")))
                    {
                        model.ConfirmPermission = "PaymentRecord0003";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("PaymentRecord0004")))
                    {
                        model.CancelPermission = "PaymentRecord0004";
                    }

                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("PaymentRecord0005")))
                    {
                        model.RevokePermission = "PaymentRecord0005";
                    }

                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("PaymentRecord0006")))
                    {
                        model.ResetPermission = "PaymentRecord0006";
                    }
                    rows.Add(model);
                }
                #endregion
                //定义页脚
                var footers = new List<PaymentRecordQueryResponse>() {
                    new PaymentRecordQueryResponse()
                    {
                        //_Id = $"单页数:{counts}",
                        MerchantOrderNo = "小计",
                        _WithdrawalAmount = sum.ToString("#0.00"),
                        _WithdrawalFee = feeSum.ToString("#0.00")
                    },
                    new PaymentRecordQueryResponse()
                    {
                        //_Id = $"总数:{count}",
                        MerchantOrderNo = "合计",
                        _WithdrawalAmount = totalAmount.ToString("#0.00"),
                        _WithdrawalFee = totalFee.ToString("#0.00")
                    }
                };
                return new DataGrid<PaymentRecordQueryResponse>()
                {
                    Total = count,
                    Rows = rows,
                    Footer = footers,
                    Success = true
                };
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<PaymentRecordQueryResponse> GetMerchantPager(PaymentRecordQuery query)
        {
            //var currentPageIndex = 0;

            //if (query.CurrentPageIndex.Value > 0)
            //{
            //    currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            //}

            var files = "p.Id,p.MerchantId,p.MerchantOrderNo,p.WithdrawalAmount,p.WithdrawalFee,p.WithdrawalBankName,p.WithdrawalCardNumber,p.WithdrawalCardName,p.PaymentStatus,p.PaymentDate,p.TransferFee,p.NoticeStatus,p.NoticeLastTime,p.NoticeTimes,p.ReqeustBody,p.NoticeFail,p.Remark,p.HandTime,p.HandBy,p.CreatedBy,p.CreatedDate,m.Name as MerchantName,(SELECT Account FROM user WHERE Id=p.HandBy) AS _HandBy,(SELECT Name FROM merchant WHERE id=p.ProxyMerchantId) as ProxyMerchantName";
            var tableName = "paymentrecord p INNER JOIN merchant m on p.MerchantId=m.Id";
            var orderby = "ORDER BY Id DESC";
            var where = $"where p.MerchantId in ({string.Join(", ", query.MerchantIds)})";

            #region 条件
            if (!string.IsNullOrEmpty(query.MerchantOrderNo))
            {
                where += string.Format(" And p.MerchantOrderNo ='{0}'", query.MerchantOrderNo);
            }

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                where += string.Format(" And p.CreatedDate between '{0}' and '{1}'", query.StartTime, query.EndTime);
            }

            if (query.PaymentStatus.HasValue)
            {
                where += string.Format(" And p.PaymentStatus ={0}", query.PaymentStatus.Value);
            }

            if (query.NoticeStatus.HasValue)
            {
                where += string.Format(" And p.NoticeStatus ={0}", query.NoticeStatus.Value);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, query.Page.Value - 1, query.Rows.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<PaymentRecordQueryResponse>();

                #region
                var rows = new List<PaymentRecordQueryResponse>();
                var sum = new decimal(0);
                var counts = 0;
                foreach (var item in list)
                {
                    sum += (item.WithdrawalAmount - item.WithdrawalFee);
                    counts++;

                    var model = new PaymentRecordQueryResponse();
                    model.Id = item.Id;
                    model._Id = item.Id.ToString();
                    model.MerchantName = item.MerchantName;
                    model.MerchantOrderNo = item.MerchantOrderNo;
                    model._WithdrawalAmount = (item.WithdrawalAmount - item.WithdrawalFee).ToString("#0.00");
                    model._WithdrawalFee = item.WithdrawalFee.ToString("#0.00");
                    model.WithdrawalBankName = item.WithdrawalBankName;
                    model.WithdrawalCardNumber = item.WithdrawalCardNumber;
                    model.WithdrawalCardName = item.WithdrawalCardName;
                    model.PaymentStatus = item.PaymentStatus;
                    model._PaymentDate = item.PaymentDate.HasValue ? item.PaymentDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model.TransferFee = item.TransferFee;
                    model.NoticeStatus = item.NoticeStatus;
                    model._NoticeLastTime = item.NoticeLastTime.HasValue ? item.NoticeLastTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model.NoticeTimes = item.NoticeTimes;
                    model.NoticeFail = item.NoticeFail;
                    model.Remark = item.Remark;
                    model._HandTime = item.HandTime.HasValue ? item.HandTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model._HandBy = string.IsNullOrEmpty(item._HandBy) ? "" : item._HandBy;
                    model._CreatedDate = item.CreatedDate.ToString("yyyy-MM-dd HH:mm:ss");
                    model.ProxyMerchantName = item.ProxyMerchantName;
                    model.CreatedDateMinutes = DateTime.Now.Subtract(item.CreatedDate).TotalMinutes;
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0002")))
                    {
                        model.AuditPermission = "ProxyPaymentRecord0002";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0003")))
                    {
                        model.ConfirmPermission = "ProxyPaymentRecord0003";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0004")))
                    {
                        model.CancelPermission = "ProxyPaymentRecord0004";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0005")))
                    {
                        model.ResetPermission = "ProxyPaymentRecord0005";
                    }
                    rows.Add(model);
                }
                //定义页脚
                var footers = new List<PaymentRecordQueryResponse>() {
                    new PaymentRecordQueryResponse()
                    {
                        _Id = $"笔数:{counts}",
                        ProxyMerchantName = "总额",
                        _WithdrawalAmount = sum.ToString("#0.00")
                    }
                };
                #endregion

                return new DataGrid<PaymentRecordQueryResponse>()
                {
                    Total = count,
                    Rows = rows,
                    Footer = footers,
                    Success = true
                };
            }
        }

        /// <summary>
        /// 商户导出查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<PaymentRecordQueryResponse> GetMerchantExportPager(PaymentRecordQuery query)
        {
            //var currentPageIndex = 0;

            //if (query.CurrentPageIndex.Value > 0)
            //{
            //    currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            //}

            var files = "p.Id,p.MerchantId,p.MerchantOrderNo,p.WithdrawalAmount,p.WithdrawalFee,p.WithdrawalBankName,p.WithdrawalCardNumber,p.WithdrawalCardName,p.PaymentStatus,p.PaymentDate,p.TransferFee,p.NoticeStatus,p.NoticeLastTime,p.NoticeTimes,p.ReqeustBody,p.NoticeFail,p.Remark,p.HandTime,p.HandBy,p.CreatedBy,p.CreatedDate,m.Name as MerchantName,u.account AS _HandBy,(SELECT Name FROM merchant WHERE id=p.ProxyMerchantId) as ProxyMerchantName";
            var tableName = "paymentrecord p INNER JOIN merchant m on p.MerchantId=m.Id   LEFT JOIN user u ON u.id=p.handby";
            var orderby = "ORDER BY Id DESC";
            var where = $"where p.MerchantId in ({string.Join(", ", query.MerchantIds)})";

            #region 条件
            if (!string.IsNullOrEmpty(query.MerchantOrderNo))
            {
                where += string.Format(" And p.MerchantOrderNo ='{0}'", query.MerchantOrderNo);
            }

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                where += string.Format(" And p.CreatedDate between '{0}' and '{1}'", query.StartTime, query.EndTime);
            }

            if (query.PaymentStatus.HasValue)
            {
                where += string.Format(" And p.PaymentStatus ={0}", query.PaymentStatus.Value);
            }

            if (query.NoticeStatus.HasValue)
            {
                where += string.Format(" And p.NoticeStatus ={0}", query.NoticeStatus.Value);
            }

            //处理人
            if (!string.IsNullOrEmpty(query.HandBy))
            {
                where += string.Format("  AND u.account='{0}'", query.HandBy);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3};", files, tableName, where, orderby);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<PaymentRecordQueryResponse>();

                #region
                var rows = new List<PaymentRecordQueryResponse>();
                var sum = new decimal(0);
                var counts = 0;
                foreach (var item in list)
                {
                    sum += (item.WithdrawalAmount - item.WithdrawalFee);
                    counts++;

                    var model = new PaymentRecordQueryResponse();
                    model.Id = item.Id;
                    model._Id = item.Id.ToString();
                    model.MerchantName = item.MerchantName;
                    model.MerchantOrderNo = item.MerchantOrderNo;
                    model._WithdrawalAmount = (item.WithdrawalAmount - item.WithdrawalFee).ToString("#0.00");
                    model._WithdrawalFee = item.WithdrawalFee.ToString("#0.00");
                    model.WithdrawalBankName = item.WithdrawalBankName;
                    model.WithdrawalCardNumber = item.WithdrawalCardNumber;
                    model.WithdrawalCardName = item.WithdrawalCardName;
                    model.PaymentStatus = item.PaymentStatus;
                    model._PaymentDate = item.PaymentDate.HasValue ? item.PaymentDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model.TransferFee = item.TransferFee;
                    model.NoticeStatus = item.NoticeStatus;
                    model._NoticeLastTime = item.NoticeLastTime.HasValue ? item.NoticeLastTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model.NoticeTimes = item.NoticeTimes;
                    model.NoticeFail = item.NoticeFail;
                    model.Remark = item.Remark;
                    model._HandTime = item.HandTime.HasValue ? item.HandTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model._HandBy = string.IsNullOrEmpty(item._HandBy) ? "" : item._HandBy;
                    model._CreatedDate = item.CreatedDate.ToString("yyyy-MM-dd HH:mm:ss");
                    model.ProxyMerchantName = item.ProxyMerchantName;
                    model.CreatedDateMinutes = DateTime.Now.Subtract(item.CreatedDate).TotalMinutes;
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0002")))
                    {
                        model.AuditPermission = "ProxyPaymentRecord0002";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0003")))
                    {
                        model.ConfirmPermission = "ProxyPaymentRecord0003";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0004")))
                    {
                        model.CancelPermission = "ProxyPaymentRecord0004";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0005")))
                    {
                        model.ResetPermission = "ProxyPaymentRecord0005";
                    }
                    rows.Add(model);
                }
                //定义页脚
                var footers = new List<PaymentRecordQueryResponse>() {
                    new PaymentRecordQueryResponse()
                    {
                        _Id = $"笔数:{counts}",
                        ProxyMerchantName = "总额",
                        _WithdrawalAmount = sum.ToString("#0.00")
                    }
                };
                #endregion

                return new DataGrid<PaymentRecordQueryResponse>()
                {
                    Total = count,
                    Rows = rows,
                    Footer = footers,
                    Success = true
                };
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<PaymentRecordQueryResponse> GetSyPager(PaymentRecordQuery query)
        {
            //var currentPageIndex = 0;

            //if (query.CurrentPageIndex.Value > 0)
            //{
            //    currentPageIndex = (query.CurrentPageIndex.Value - 1) * query.PageSize.Value;
            //}

            var files = "p.Id,p.MerchantId,p.MerchantOrderNo,p.WithdrawalAmount,p.WithdrawalFee,p.WithdrawalBankName,p.WithdrawalCardNumber,p.WithdrawalCardName,p.PaymentStatus,p.PaymentDate,p.TransferFee,p.NoticeStatus,p.NoticeLastTime,p.NoticeTimes,p.ReqeustBody,p.NoticeFail,p.Remark,p.HandTime,p.HandBy,p.CreatedBy,p.CreatedDate,m.Name as MerchantName,(SELECT Account FROM user WHERE Id=p.HandBy) AS _HandBy,(SELECT Name FROM merchant WHERE id=p.ProxyMerchantId) as ProxyMerchantName";
            var tableName = "paymentrecord p INNER JOIN merchant m on p.MerchantId=m.Id";
            var orderby = "ORDER BY Id DESC";
            var where = $"where 1=1";

            #region 条件
            if (!string.IsNullOrEmpty(query.MerchantOrderNo))
            {
                where += string.Format(" And p.MerchantOrderNo ='{0}'", query.MerchantOrderNo);
            }

            if (!string.IsNullOrEmpty(query.StartTime) && !string.IsNullOrEmpty(query.EndTime))
            {
                where += string.Format(" And p.CreatedDate between '{0}' and '{1}'", query.StartTime, query.EndTime);
            }
            if (query.MerchantId.HasValue)//所属商户ID
            {
                where += string.Format(" And p.MerchantId ={0}", query.MerchantId.Value);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, query.Page.Value - 1, query.Rows.Value);

            using (var multi = _dbSession.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<PaymentRecordQueryResponse>();

                #region
                var rows = new List<PaymentRecordQueryResponse>();

                var counts = new decimal(0);
                var sum = new decimal(0);
                var fee = new decimal(0);

                foreach (var item in list)
                {
                    sum += item.WithdrawalAmount;

                    var model = new PaymentRecordQueryResponse();

                    model.Id = item.Id;
                    model._Id = item.Id.ToString();
                    model.MerchantName = item.MerchantName;
                    model.MerchantOrderNo = item.MerchantOrderNo;
                    model._WithdrawalAmount = (item.WithdrawalAmount - item.WithdrawalFee).ToString("#0.00");
                    model._WithdrawalFee = item.WithdrawalFee.ToString("#0.00");
                    model.WithdrawalBankName = item.WithdrawalBankName;
                    model.WithdrawalCardNumber = item.WithdrawalCardNumber;
                    model.WithdrawalCardName = item.WithdrawalCardName;
                    model.PaymentStatus = item.PaymentStatus;
                    model._PaymentDate = item.PaymentDate.HasValue ? item.PaymentDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model.TransferFee = item.TransferFee;
                    model.NoticeStatus = item.NoticeStatus;
                    model._NoticeLastTime = item.NoticeLastTime.HasValue ? item.NoticeLastTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model.NoticeTimes = item.NoticeTimes;
                    model.NoticeFail = item.NoticeFail;
                    model.Remark = item.Remark;
                    model._HandTime = item.HandTime.HasValue ? item.HandTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
                    model._HandBy = string.IsNullOrEmpty(item._HandBy) ? "" : item._HandBy;
                    model._CreatedDate = item.CreatedDate.ToString("yyyy-MM-dd HH:mm:ss");
                    model.ProxyMerchantName = item.ProxyMerchantName;
                    model.CreatedDateMinutes = DateTime.Now.Subtract(item.CreatedDate).TotalMinutes;
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0002")))
                    {
                        model.AuditPermission = "ProxyPaymentRecord0002";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0003")))
                    {
                        model.ConfirmPermission = "ProxyPaymentRecord0003";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0004")))
                    {
                        model.CancelPermission = "ProxyPaymentRecord0004";
                    }
                    if (query.UserPermission != null && query.UserPermission.Any(c => c.Contains("ProxyPaymentRecord0005")))
                    {
                        model.ResetPermission = "ProxyPaymentRecord0005";
                    }
                    rows.Add(model);
                }
                //定义页脚
                var footers = new List<PaymentRecordQueryResponse>() {
                    new PaymentRecordQueryResponse()
                    {
                        //_Id = null,
                        //MerchantName = "",
                        ProxyMerchantName = "总额",
                        _WithdrawalAmount = sum.ToString("#0.00")
                    }
                };
                #endregion

                return new DataGrid<PaymentRecordQueryResponse>()
                {
                    Total = count,
                    Rows = rows,
                    Footer = footers,
                    Success = true
                };
            }
        }
    }
}
